package com.example.tnot.Teacher.CoursePart.Container;

import static com.example.tnot.login.fragmentui.LoginFragment.BASE_URL;
import static com.example.tnot.login.fragmentui.LoginFragment.teacher_data;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.tnot.R;
import com.example.tnot.Teacher.ActivityConfig.TeacherHomeActivity;
import com.example.tnot.Teacher.CoursePart.ItemBean.rv_MyStudyListItem;
import com.example.tnot.Teacher.CoursePart.ItemBean.rv_MyTeachListItem;
import com.example.tnot.Teacher.CoursePart.adapter.rvMyStudyAdapter;
import com.example.tnot.Teacher.CoursePart.adapter.rvMyTeachAdapter;
import com.example.tnot.Util.popupwindow.FloatWindowService;
import com.example.tnot.api.HttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class CourseContainerFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

   // private String teacher_name = teacher_data.getString("username");
    View view;
    TextView tv_teach, tv_study;
    RecyclerView rv_course;
    List<rv_MyTeachListItem> courses; // 我教的课程列表
    List<rv_MyStudyListItem> StudyCourses; // 我学的课程列表
    private rvMyTeachAdapter teachAdapter; // 复用的"我教的课"适配器
    private rvMyStudyAdapter studyAdapter; // 复用的"我学的课"适配器
    Boolean flag_teach; // 切换标识：true=显示我教的课，false=显示我学的课
    private BroadcastReceiver floatWindowReceiver;
    private String Add_course_name, Add_cover_uri;
    private String mParam1;
    private String mParam2;
    private Uri coverUri;
    private rvMyStudyAdapter.MarginItemDecoration marginDecoration;


    public CourseContainerFragment() throws JSONException {
    }

    public static CourseContainerFragment newInstance(String param1, String param2) throws JSONException {
        CourseContainerFragment fragment = new CourseContainerFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        // 初始化广播接收器
        floatWindowReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("aboutstuFragment", "接收到广播: " + intent.getAction());
                if ("com.example.tnot.Course.Click.Item".equals(intent.getAction())) {
                    Log.d("CourseContainerFragment", "处理悬浮窗点击事件");
                    // 确保在主线程中执行导航操作
                    if (getActivity() != null && getView() != null) {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    NavController navController = Navigation.findNavController(getView());
                                    navController.navigate(R.id.action_courseContainerFragment_to_addCourseFragment2);
                                } catch (Exception e) {
                                }
                            }
                        });
                    }
                }
            }
        };
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.course_container_fragment, container, false);
//        if (getArguments() != null){
//            String course_name = getArguments().getString("course_name");
//            Log.d("course_name", course_name);
//        }


        // 1. 先初始化数据列表（必须在适配器前初始化）
        courses = new ArrayList<>();
        StudyCourses = new ArrayList<>();

        // 2. 初始化适配器（绑定已初始化的列表，确保唯一关联）
        teachAdapter = new rvMyTeachAdapter(courses);
        studyAdapter = new rvMyStudyAdapter(StudyCourses);

        // 3. 绑定视图
        tv_teach = view.findViewById(R.id.tv_teach);
        tv_study = view.findViewById(R.id.tv_study);
        rv_course = view.findViewById(R.id.rv_course);

        // 4. 初始化界面和数据
        try {
            InitInterface();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }

        // 5. 切换按钮点击事件
        tv_teach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SwitchTeach();
                flag_teach = true;
                AdapterChange();
            }
        });

        tv_study.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SwitchStudy();
                flag_teach = false;
                AdapterChange();
            }
        });

//
//        // 设置Fragment根视图到悬浮窗服务
//        FloatWindowService.setFragmentRootView(view);
//
//        // 设置滚动监听（如果需要跟随滚动）
//        setupScrollListener(view);


        return view;
    }

//    private void setupScrollListener(View rootView) {
//        // 如果你的Fragment有滚动视图（如RecyclerView、ScrollView等）
//        // 添加滚动监听来更新悬浮窗位置
//
//        View scrollView = rootView.findViewById(R.id.rv_course); // 替换为你的滚动视图ID
//
//        if (scrollView instanceof RecyclerView) {
//            ((RecyclerView) scrollView).addOnScrollListener(new RecyclerView.OnScrollListener() {
//                @Override
//                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
//                    super.onScrolled(recyclerView, dx, dy);
//                    updateFloatingWindowPosition();
//                }
//            });
//        } else if (scrollView instanceof ScrollView) {
//            scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
//                @Override
//                public void onScrollChanged() {
//                    updateFloatingWindowPosition();
//                }
//            });
//        }
//    }
//
//    private void updateFloatingWindowPosition() {
//        Intent intent = new Intent(getActivity(), FloatWindowService.class);
//        intent.setAction("UPDATE_POSITION");
//        getActivity().startService(intent);
//    }

    /**
     * 切换适配器（复用全局适配器，避免重复创建）
     */
    private void AdapterChange() {
        rv_course.setLayoutManager(new LinearLayoutManager(getActivity()));

        // 先移除旧的间距装饰器
        if (rv_course.getItemDecorationCount() > 0) {
            rv_course.removeItemDecorationAt(0);
        }

        if (flag_teach) {
            // 显示"我教的课"
            rv_course.setAdapter(teachAdapter);
            marginDecoration = new rvMyStudyAdapter.MarginItemDecoration(15, 10, 36, 36);
        } else {
            // 显示"我学的课"
            rv_course.setAdapter(studyAdapter);
            marginDecoration = new rvMyStudyAdapter.MarginItemDecoration(8, 10, 36, 36);
        }

        // 添加新的间距装饰器
        rv_course.addItemDecoration(marginDecoration);
    }


    /**
     * 初始化界面默认状态
     */
    private void InitInterface() throws JSONException {
        // 默认选中"我教的课"
        tv_study.setBackgroundColor(0x1E1F22FF);
        tv_teach.setBackgroundColor(0xFFFFFFFF);
        flag_teach = true;

        // 初始化数据（先加载本地测试数据，再加载网络数据）
        InitCourse(); // 加载"我的课程"网络数据

        // 初始显示"我教的课"
        AdapterChange();
    }

    /**
     * 加载"我教的课"数据（网络请求）
     */
    private void InitCourse() throws JSONException {
        String URL = BASE_URL+"api/get_course";
        HashMap<String, String> params = new HashMap<>();

        if(teacher_data != null)
        {
            params.put("id", teacher_data.getString("id"));
        }
        else
        {
            params.put("id","1001");
        }
        String jsonData = HttpUtils.buildJsonString(params);


        HttpUtils.sendPostRequest(URL, jsonData, new HttpUtils.HttpCallback() {
            @Override
            public void onSuccess(String response) throws JSONException {
                Log.d("教师信息", "网络请求成功，响应数据：" + response);
                InitCourse2(response); // 解析并添加数据
                // 主线程刷新适配器
                refreshTeachAdapter();
            }

            @Override
            public void onFailure(String errorMsg) {
                Log.e("CourseContaineFragment界面，教师信息", "教师信息获取失败：" + errorMsg);
                // 网络失败时添加测试数据（方便调试）
                addTestTeachData();
                addTestStudyData();
                // 主线程刷新适配器
                refreshTeachAdapter();
            }
        });
    }

    /**
     * 解析网络数据并添加到列表
     */
//     仅修改 InitCourse2 方法中的数据添加逻辑
    private void InitCourse2(String response) throws JSONException {
        JSONArray jsonArray = new JSONArray(response);

        JSONArray datas = jsonArray.getJSONObject(2).getJSONArray("data");

        JSONArray teach_datas= (JSONArray) datas.get(0);
        JSONArray study_datas= (JSONArray) datas.get(1);
        //Log.d("获取","获取到的数据"+study_datas.toString());

        for (int i = 0; i < teach_datas.length(); i++) {
            JSONObject data = teach_datas.getJSONObject(i);
            String courseName = data.getString("course_name");
            String teacherName = data.getString("teacher_name");
            JSONArray classArray = data.getJSONArray("class_list");

            // 解析班级列表
            List<String> classList = new ArrayList<>();
            for (int j = 0; j < classArray.length(); j++) {
                //JSONObject class_data= (JSONObject) classArray.get(j);
                classList.add(classArray.get(j).toString());
            }

            String courseId = data.getString("course_id");

            // 构造列表项：第一个参数传入course_id（适配器会自动构建图片URL）
            courses.add(new rv_MyTeachListItem(
                    courseId,
                    courseName,
                    teacherName,
                    classList
            ));

            // 移除没有班级的课程
            for (rv_MyTeachListItem list : courses){
                if(list.getCourse_classes().isEmpty()){
                    courses.remove(list);
                }
            }


            Log.d("添加", "我教的课添加成功：" + courseName);
        }

        for (int i = 0; i < study_datas.length(); i++){
            JSONObject data = study_datas.getJSONObject(i);
            String courseId= data.getString("course_id");
            String teacherName = data.getString("teacher_name");
            String courseName = data.getString("course_name");
            StudyCourses.add(new rv_MyStudyListItem(courseName, teacherName,
                    R.drawable.example_face, courseId));
        }


    }


    /**
     * 添加测试数据（网络失败/解析失败时用）
     */
    private void addTestTeachData() {
        courses.add(new rv_MyTeachListItem(
                "0",
                "英语（测试）",
                "张老师",
                Arrays.asList("2304班", "2001班")
        ));
        Log.d("添加", "测试数据添加成功");
    }

    private void addTestStudyData() {
        StudyCourses.add(new rv_MyStudyListItem("计算机技术", "莉莉", R.drawable.example_face,"1"));
        Log.d("添加", "测试数据添加成功");
    }

    private void refreshTeachAdapter() {
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (teachAdapter != null) {
                        teachAdapter.notifyDataSetChanged();
                        Log.d("刷新", "适配器已刷新，课程总数：" + courses.size());
                    }
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 注册广播接收器
        if (floatWindowReceiver != null && getActivity() != null) {
            IntentFilter filter = new IntentFilter("com.example.tnot.Course.Click.Item");
            LocalBroadcastManager.getInstance(getActivity()).registerReceiver(floatWindowReceiver, filter);
            Log.d("CourseContainerFragment", "广播接收器已注册");
        }

        // 启动悬浮窗服务
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(getActivity())) {
            startFloatWindowService();
        }

        // 显示底部导航栏
        if (getActivity() instanceof TeacherHomeActivity) {
            ((TeacherHomeActivity) getActivity()).showBottomNavigation();
            ((TeacherHomeActivity) getActivity()).enableViewPagerSwipe();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 注销广播接收器
        try {
            if (floatWindowReceiver != null && getActivity() != null) {
                LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(floatWindowReceiver);
                Log.d("CourseContainerFragment", "广播接收器已注销");
            }
        } catch (IllegalArgumentException e) {
            Log.w("CourseContainerFragment", "广播接收器未注册或已注销", e);
        }
        hideFloatingWindow();
        // 停止悬浮窗服务
        stopFloatWindowService();
    }


    // 通过广播或服务调用显示和隐藏方法
    private void showFloatingWindow() {
        Intent intent = new Intent(getActivity(), FloatWindowService.class);
        intent.setAction("SHOW");
        getActivity().startService(intent);
    }

    private void hideFloatingWindow() {
        Intent intent = new Intent(getActivity(), FloatWindowService.class);
        intent.setAction("HIDE");
        getActivity().startService(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 确保停止服务
        hideFloatingWindow();
        stopFloatWindowService();
    }

    private void startFloatWindowService() {
        Intent intent = new Intent(getActivity(), FloatWindowService.class);
        getActivity().startService(intent);
    }

    private void stopFloatWindowService() {
        Intent intent = new Intent(getActivity(), FloatWindowService.class);
        getActivity().stopService(intent);
    }

    /**
     * 切换到"我教的课"样式
     */
    private void SwitchTeach() {
        tv_teach.setBackgroundColor(0xFFFFFFFF);
        tv_study.setBackgroundColor(0x1E1F22FF);
    }

    /**
     * 切换到"我学的课"样式
     */
    private void SwitchStudy() {
        tv_teach.setBackgroundColor(0x1E1F22FF);
        tv_study.setBackgroundColor(0xFFFFFFFF);
    }
}